package com.log.compone;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

public class MyLogger implements LogAble, Runnable {

    BlockingQueue<String> logCache;
    OutputStream writer;
    AtomicInteger counter = new AtomicInteger(0);
    public MyLogger(OutputStream writer) {
        this.writer = new BufferedOutputStream(writer);
        logCache = new LinkedBlockingQueue<>(1024 * 1024);
        new Thread(this).start();
    }

    @Override
    public void print(String msg) throws InterruptedException {
        logCache.put(msg);
        counter.incrementAndGet();
    }

    @Override
    public void run() {
        String msg;
        while (true) {
            try {
                msg = logCache.take();
                if (msg != null) {
                    writer.write(msg.getBytes());
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
